package com.wifi.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.SparseArray;

import java.io.InputStream;

public class ImageCache {
	private static final String TAG = "ImageCache";
	private static SparseArray<Bitmap> mBitmapCache = new SparseArray<Bitmap>();
	private static Context mContext;
	
	private static int memoryClass;
	
	public static BitmapFactory.Options bitmapOptions;
	
	public static BitmapFactory.Options getBitmapOptions(){
		return bitmapOptions;
	}
	
	public static void init(Context context){
		mContext = context;
		

		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		memoryClass = am.getMemoryClass();
//		Log.v("MEMORY", "memoryClass:" + Integer.toString(memoryClass));
		
		bitmapOptions = new BitmapFactory.Options();   
		bitmapOptions.inPurgeable = true;
		bitmapOptions.inInputShareable = true;
//		opt.inSampleSize = 2;		//没有效果？！
		
		if(memoryClass <= 64){ //似乎30M的限制还是很多会OOM。到64M吧。魅族是96M没有出现明显的OOM
			bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
		}
		else{
			bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_4444;
		}
			
	}
	
	public static void clearBitmap(int resid){
		try {
			Bitmap bitmap = mBitmapCache.get(resid);
			if(bitmap != null){
				bitmap.recycle();
				mBitmapCache.remove(resid);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Bitmap getBitmap(int resid){
		Bitmap bitmap = mBitmapCache.get(resid);
		if(bitmap == null){
			bitmap = createBitmap(resid);
			mBitmapCache.put(resid, bitmap);
//			Log.d(TAG,"new createBitmap");
		}else{
//			Log.d(TAG,"with directly");
		}
//		Log.d(TAG,resid +" bitmap size:" + bitmap.getAllocationByteCount() + " " + bitmap.getByteCount());
		return bitmap;
	}

	private static Bitmap createBitmap(int resid) {
		//获取资源图片
		InputStream is = mContext.getResources().openRawResource(resid);
		Bitmap bmp = null;
		try{
			bmp = BitmapFactory.decodeStream(is,null,getBitmapOptions());
		}catch(OutOfMemoryError e){
//			Log.e(TAG,"setBackgroundImage OOM");
		}
		return bmp;
	}

	public static void updateImage(int resid, Bitmap image) {
		mBitmapCache.put(resid, image);
	}
}
